package gui.views;

import controller.Controller;
import core.Model;
import core.utils.Variable;
import gui.actions.CheckboxAction;
import gui.utils.CheckBoxWithVariable;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class OptionsView extends JPanel implements ActionListener {
	private static final long serialVersionUID = 1L;

	private final MapsView mv;
	
	public OptionsView(MapsView mv) {
		this.mv = mv;

		CheckBoxWithVariable cb;

		// Create iterator and use it to loop through all variables and create
		// the appropriate checkboxes.
		List<Variable> variables = Model.getVariables();
		CheckboxAction action = new CheckboxAction();
		for (Variable var : variables) {
			//System.out.println("Creating checkbox with variable " + var);
			cb = new CheckBoxWithVariable(var, action);
			cb.addActionListener(this);
			cb.setEnabled(false);
			add(cb);
		}
	}

	/**
	 * Fired when a checkbox is (un)selected.
	 */
	@Override
	public void actionPerformed(ActionEvent evt) {
		CheckBoxWithVariable cb = (CheckBoxWithVariable) evt.getSource();

		Controller.getInstance().checkBoxClicked(cb.getVariable(), cb.isSelected());
		if(!mv.isActive()) {
			//TODO - What is this even supposed to do?
			//mv.add(MapFactory.createMap((XmlParser.GetCoordinates(cb.getVariable()))));
			mv.setActive(true);

		}
	}

	public void update() {
		boolean connected = Model.getInstance().isConnected();
		Component[] components = getComponents();
        for (Component component : components) {
            if (component instanceof CheckBoxWithVariable) {
                CheckBoxWithVariable cb = (CheckBoxWithVariable) component;
                cb.setEnabled(connected);
            }
        }
	}
}
